package com.ruoyi.web.controller;

import com.ruoyi.business.Customer;
import com.ruoyi.business.enums.CitySplit;
import com.ruoyi.business.enums.DealEnum;
import com.ruoyi.business.enums.EffectiveEnum;
import com.ruoyi.business.qo.CustomerQO;
import com.ruoyi.business.service.CustomerService;
import com.ruoyi.common.common.CommonEnum;
import com.ruoyi.common.common.GlobalValue;
import com.ruoyi.common.common.ResultBody;
import com.ruoyi.common.utils.IpUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @title: CustomerController
 * @copyright: copyright (c) 2021
 * @author: jiangguanjun
 * @date: 2023/1/29 14:56
 * @firstReview:
 * @lastReview:
 * @desc: 客户留言相关
 */
@Api(value = "CustomerController", tags = "留言相关")
@RestController
@Slf4j
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CustomerService customerService;

    @Value("${city.path}")
    private String path  ;


    @CrossOrigin
    @PostMapping("/add")
    @ApiOperation(value = "添加留言,cuPhone必填")
    public ResultBody add(@RequestBody Customer customer, HttpServletRequest request){

        // 校验必填参数
        boolean  b = checkParam(customer);
        if(!b){
            return ResultBody.error(CommonEnum.REGISTER_PARAM_ERROR) ;
        }
        String ip = IpUtil.getIpAddrs(request) ;
        log.info("ip:::::::::{}",ip);
        customer.setCuIp(ip);

        Searcher searcher = null;
        try {
            searcher = Searcher.newWithFileOnly(path);
        } catch (IOException e) {
            log.error("failed to create searcher with : {}", path, e);
            return null;
        }
        String city = IpUtil.getCityDetailByIp(ip,searcher,",", CitySplit.province.getIndex(),CitySplit.city.getIndex()) ;
        customer.setCuAddress(city);

        // 校验是否重复提交
        Object cacheIp = redisTemplate.opsForValue().get(GlobalValue.getCustomerRedisKey(customer.getCuIp())) ;
        if(cacheIp != null ){
            log.info(CommonEnum.CUSTOMER_COMMIT_REPEAT_ERROR.getResultMsg()+"{}",customer);
            return ResultBody.error(CommonEnum.CUSTOMER_COMMIT_REPEAT_ERROR) ;
        }

        return customerService.add(customer) ;
    }

    @CrossOrigin
    @PostMapping("/getCity")
    @ApiOperation(value = "获取当前城市")
    public ResultBody getCity(HttpServletRequest request){


        String ip = IpUtil.getIpAddrs(request) ;
        log.info("ip:::::::::{}",ip);


        Searcher searcher = null;
        try {
            searcher = Searcher.newWithFileOnly(path);
        } catch (IOException e) {
            log.error("failed to create searcher with : {}", path, e);
            return null;
        }
        String city = IpUtil.getCityDetailByIp(ip,searcher,"", CitySplit.province.getIndex(),CitySplit.city.getIndex()) ;


        return ResultBody.success(city) ;
    }


    @CrossOrigin
    @PostMapping("/list")
    @ApiOperation(value = "获取留言列表 页面：客服-留言列表")
    public ResultBody list(@RequestBody CustomerQO customerQO){
        if(customerQO.getStartTime() != null){
            customerQO.setStartTime(customerQO.getStartTime()+" 00:00:00");
        }

        if(customerQO.getEndTime() != null){
            customerQO.setEndTime(customerQO.getEndTime()+" 23:59:59");
        }
        return customerService.queryPage(customerQO) ;
    }
    @CrossOrigin
    @PostMapping("/deal")
    @ApiOperation(value = "处理留言  页面：客服-留言列表-处理")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "留言的id", dataType = "Integer"),
            @ApiImplicitParam(name = "op", value = "操作，1：有效信息，0：无效信息", dataType = "Integer")
    })
    public ResultBody deal(@RequestParam Integer id,@RequestParam Integer op){
        log.info("id::{},op::{}",id,op);

        Long userId = SecurityUtils.getUserId() ;
        log.info("userId:::{}",userId);
        if(!EffectiveEnum.checkExist(op)){
            log.error(CommonEnum.CUSTOMER_DEAL_PARAM_ERROR.getResultMsg());
            return ResultBody.error(CommonEnum.CUSTOMER_DEAL_PARAM_ERROR) ;
        }
        if(!DealEnum.checkExist(op)){
            log.error(CommonEnum.CUSTOMER_DEAL_PARAM_ERROR.getResultMsg());
            return ResultBody.error(CommonEnum.CUSTOMER_DEAL_PARAM_ERROR) ;
        }
        Customer customer = customerService.getById(id) ;
        if(customer == null ){
            log.error(CommonEnum.CUSTOMER_NOT_EXIST_ERROR.getResultMsg());
            return ResultBody.error(CommonEnum.CUSTOMER_NOT_EXIST_ERROR) ;
        }
        if(DealEnum.DEAL_FINAL.getCode().equals(customer.getDeal()) || customer.getEffective().equals(op) ){
            log.error(CommonEnum.CUSTOMER_NOT_REPEAT_ERROR.getResultMsg());
            return ResultBody.error(CommonEnum.CUSTOMER_NOT_REPEAT_ERROR) ;
        }

        return customerService.deal(id,op,userId) ;
    }

    /**
     * @author jiangguanjun
     * @date 2023/1/29 15:26
     * @param
     * @return
     * @desc 校验参数
     */
    private boolean checkParam(Customer customer) {
        if(StringUtils.isAnyBlank(customer.getCuPhone())){
            log.info("缺少参数：{}",customer);
            return false ;
        }
        return true ;
    }


}
